package com.ksyun.campus.metaserver.controller;

import com.ksyun.campus.metaserver.domain.dto.ApiResponse;
import com.ksyun.campus.metaserver.services.LeaderElectionService;
import com.ksyun.campus.metaserver.services.MetadataSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import java.util.Map;

/**
 * 同步控制器
 * 提供元数据同步相关的API
 */
@Slf4j
@RestController
@RequestMapping("/admin/sync")
public class SyncController {
    
    @Autowired
    private LeaderElectionService leaderElection;
    
    @Autowired
    private MetadataSyncService syncService;
    
    /**
     * 获取同步事件（供 Follower 拉取）
     */
    @GetMapping("/events")
    public ResponseEntity<?> getSyncEvents(
            @RequestParam(value = "from", defaultValue = "0") long fromSequence,
            @RequestParam(value = "limit", defaultValue = "100") int limit) {
        
        try {
            if (!leaderElection.isLeader()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("只有 Leader 可以提供同步事件"));
            }
            
            // TODO: 实现获取同步事件的逻辑
            // 这里需要从 ZooKeeper 或本地存储中获取指定范围的同步事件
            
            return ResponseEntity.ok(ApiResponse.success(new MetadataSyncService.SyncEvent[0]));
            
        } catch (Exception e) {
            log.error("获取同步事件失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("获取同步事件失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取同步状态
     */
    @GetMapping("/status")
    public ResponseEntity<?> getSyncStatus() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 当前实例信息
            result.put("currentInstance", leaderElection.getCurrentInstance());
            result.put("isLeader", leaderElection.isLeader());
            result.put("currentSyncStatus", syncService.getCurrentSyncStatus());
            
            // 如果是 Leader，返回所有 Follower 的同步状态
            if (leaderElection.isLeader()) {
                result.put("followerSyncStatus", syncService.getAllFollowerSyncStatus());
                
                // 获取当前 Leader 信息
                try {
                    result.put("currentLeader", leaderElection.getCurrentLeader());
                } catch (Exception e) {
                    log.warn("获取 Leader 信息失败", e);
                }
            }
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("获取同步状态失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("获取同步状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 强制触发同步（测试用）
     */
    @PostMapping("/trigger")
    public ResponseEntity<?> triggerSync() {
        try {
            if (!leaderElection.isLeader()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("只有 Leader 可以触发同步"));
            }
            
            // 发布一个测试同步事件
            Map<String, Object> testData = new HashMap<>();
            testData.put("test", true);
            testData.put("timestamp", System.currentTimeMillis());
            
            syncService.publishSyncEvent(
                    MetadataSyncService.SyncEventType.METADATA_UPDATE,
                    "/test/sync",
                    testData
            );
            
            return ResponseEntity.ok(ApiResponse.success("同步事件已发布"));
            
        } catch (Exception e) {
            log.error("触发同步失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("触发同步失败: " + e.getMessage()));
        }
    }
    
    /**
     * 强制放弃 Leader 身份（测试用）
     */
    @PostMapping("/release-leadership")
    public ResponseEntity<?> releaseLeadership() {
        try {
            if (!leaderElection.isLeader()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("当前实例不是 Leader"));
            }
            
            leaderElection.releaseLeadership();
            
            return ResponseEntity.ok(ApiResponse.success("Leader 身份已释放"));
            
        } catch (Exception e) {
            log.error("释放 Leader 身份失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("释放 Leader 身份失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取集群成员信息
     */
    @GetMapping("/cluster")
    public ResponseEntity<?> getClusterInfo() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 当前实例信息
            result.put("currentInstance", leaderElection.getCurrentInstance());
            result.put("isLeader", leaderElection.isLeader());
            
            // Leader 信息
            try {
                result.put("currentLeader", leaderElection.getCurrentLeader());
            } catch (Exception e) {
                log.warn("获取 Leader 信息失败", e);
                result.put("currentLeader", null);
            }
            
            // 集群成员信息
            result.put("clusterMembers", leaderElection.getClusterMembers());
            
            // 健康状态
            result.put("isHealthy", leaderElection.isHealthy());
            
            return ResponseEntity.ok(ApiResponse.success(result));
            
        } catch (Exception e) {
            log.error("获取集群信息失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("获取集群信息失败: " + e.getMessage()));
        }
    }
}
